﻿CREATE TRIGGER [dbo].[tr_LoanInfo_Snapshot_UPDATE]
ON [dbo].[t_LoanInfo_Snapshot]
FOR UPDATE
AS

IF @@ROWCOUNT = 0 RETURN

-- TODO: implement payment check for states with addon limitation
--IF UPDATE (PaymentOverride) BEGIN
--	DECLARE @PmtMax numeric(18,2),@PmtOver numeric(18,2)
--	SELECT @PmtMax = Payment_Max,@PmtOver = ISNULL(PaymentOverride,0) FROM v_LoanInfo
--	WHERE LoanID IN(SELECT LoanID FROM inserted) AND Payment_Max < PaymentOverride
--	IF @PmtMax < @PmtOver BEGIN
--		ROLLBACK TRAN
--		DECLARE @Text nvarchar(256) SET @Text = dbo.sprint2('Payment %s is greater than maximum %s, allowed by state.',@PmtOver,@PmtMax)
--		RAISERROR(@Text,16,1)
--		RETURN
--	END
--END

-- FirstPaymentDate
IF UPDATE(ContractDate) OR UPDATE(PaymentsPerYear)
	UPDATE t_LoanInfo_Snapshot SET FirstPaymentDate =
		CASE LI_S.PaymentsPerYear
			 WHEN 12 THEN DATEADD(mm,1,LI_S.ContractDate)
			 WHEN 24 THEN DATEADD(dd,15,LI_S.ContractDate)
			 WHEN 26 THEN DATEADD(wk,2,LI_S.ContractDate)
			 WHEN 52 THEN DATEADD(wk,1,LI_S.ContractDate)
		END
	FROM t_LoanInfo_Snapshot LI_S INNER JOIN inserted i
		ON LI_S.LoanID = i.LoanID AND LI_S.SnapshotName = i.SnapshotName

-- NumberOfPayments
IF UPDATE(PaymentsPerYear)
	DECLARE @PaymentsPerYear_Prev float SELECT @PaymentsPerYear_Prev = PaymentsPerYear FROM deleted
	DECLARE @Years float SELECT @Years = NumberOfPayments / @PaymentsPerYear_Prev FROM inserted
	--IF @Years = CONVERT(int,@Years)
		UPDATE LI_S SET NumberOfPayments = ROUND(@Years * LI_S.PaymentsPerYear,0)
		FROM t_LoanInfo_Snapshot LI_S INNER JOIN inserted i
			ON LI_S.LoanID = i.LoanID AND LI_S.SnapshotName = i.SnapshotName AND LI_S.NumberOfPayments <> @Years * LI_S.PaymentsPerYear